package com.juanpi.order.common.utils;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Map;

public class HttpClientUtil {

    private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);


    public static String doPost(final String url, final String postData,Map<String,String> header) {
        CloseableHttpClient httpClient = null;
        // post请求
        HttpPost httpPost = new HttpPost(url);
        String result = "";
        try {
            httpClient = HttpClients.custom().build();
            // 设置HTTP请求的超时连接时间和socket连接时间
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build();//设置请求和传输超时时间

            // post请求参数输入
            StringEntity postEntity = new StringEntity(postData, "UTF-8");
            httpPost.setEntity(postEntity);
            httpPost.setConfig(requestConfig);
            if(header!=null){
                for(String key:header.keySet()){
                    if(StringUtils.isNotEmpty(header.get(key))){
                        httpPost.addHeader(key, header.get(key));
                    }
                }
            }


            logger.info("httpRequest.doPost begin,param url:{},httpPost:{},postData:{}", url, JsonMapper.toJson(httpPost),postData);
            // 请求HTTP请求
            HttpResponse response = httpClient.execute(httpPost);

            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                result = EntityUtils.toString(entity, "UTF-8");
            } else {
                throw new RuntimeException(""+response.getStatusLine().getStatusCode());
            }
            logger.info("return code :{}", response.getStatusLine().getStatusCode());
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            // 关闭连接
            httpPost.abort();
            httpPost.releaseConnection();
            try {
                httpClient.close();
            } catch (IOException e) {
            }
        }
        return result;
    }

    public static String doGet(String url,Map<String,String> header) {
        CloseableHttpClient httpClient = null;

        // get请求
        HttpGet httpGet = new HttpGet(url);
        String result = "";
        try {

            httpClient = HttpClients.custom().build();
            // 设置HTTP请求的超时连接时间和socket连接时间
            Integer connTime = 5000;
            Integer socketTime = 5000;
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(socketTime)
                    .setConnectTimeout(connTime).build();// 设置请求和传输超时时间
            httpGet.setConfig(requestConfig);
            httpGet.addHeader("Content-Type", "text/xml");

            //添加UA
            if(header!=null){
                for(String key:header.keySet()){
                    if(StringUtils.isNotEmpty(header.get(key))){
                        httpGet.addHeader(key, header.get(key));
                    }
                }
            }

            logger.info("httpRequest.doGet begin ,param:{}", url);

            // 请求HTTP请求
            HttpResponse response = httpClient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                result = EntityUtils.toString(entity, "UTF-8");
            }
        } catch (IllegalArgumentException e) {
            logger.error("doGet IllegalArgumentException. PayNo: {}");
        } catch (ClientProtocolException e) {
            logger.error("doGet ClientProtocolException. PayNo: {}");
        } catch (IOException e) {
            logger.error("doGet IOException. PayNo: {}");
        } finally {
            // 关闭连接
            httpGet.abort();
            httpGet.releaseConnection();
            try {
                httpClient.close();
            } catch (IOException e) {
                logger.error("", e);
            }
        }
        return result;
    }


}